//
//  CallStarLeavewordViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2017/5/2.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "CallStarLeavewordViewController.h"
#import "CallStarLeaveCell.h"
#import "SuperCommentModel.h"

@interface CallStarLeavewordViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    NSMutableArray *_leaveListArray;
    UITextField *_msgInputFeild;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *msgInputView;
@end

@implementation CallStarLeavewordViewController

- (UIView *)msgInputView {
    if (!_msgInputView) {
        //输入框
        _msgInputView = [[UIView alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT -kNAV_HEIGHT- 50, kSCREEN_WIDTH, 50 )];
        _msgInputView.backgroundColor = [UIColor whiteColor];
        UIView *sepline = [[UIView alloc] init];
        [_msgInputView addSubview:sepline];
        sepline.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 0.5);
        sepline.backgroundColor = [UIColor cellLineColor];
        UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sendBtn.frame = CGRectMake(self.view.width - 15 - 50, 0, 50, 50);
        [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [sendBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [sendBtn setTitleColor:UIColorFromRGB(0x0ACCAC) forState:UIControlStateNormal];
        [sendBtn setBackgroundColor:[UIColor clearColor]];
        [sendBtn addTarget:self action:@selector(clickSend:) forControlEvents:UIControlEventTouchUpInside];
        
        _msgInputFeild = [[UITextField alloc] initWithFrame:CGRectMake(10,7.5,sendBtn.left - 20,30)];
        _msgInputFeild.backgroundColor = [UIColor clearColor];
        _msgInputFeild.returnKeyType = UIReturnKeySend;
        _msgInputFeild.borderStyle = UITextBorderStyleRoundedRect;
        _msgInputFeild.placeholder = @"留下你想对明星说的话...";
        _msgInputFeild.delegate = self;
        _msgInputFeild.textColor = [UIColor blackColor];
        _msgInputFeild.font = [UIFont systemFontOfSize:14];
        
        [_msgInputView addSubview:_msgInputFeild];
        [_msgInputView addSubview:sendBtn];
        
    }
    return _msgInputView;
}


#pragma mark -- 呼唤明星留言列表
- (void)leaveWordListRequest {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"cid":self.cid,
                           @"type":@"10",
                           @"page":@"1"
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:KSCommentList];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            NSArray *array = responseObject[@"data"][@"list"];
            for (NSDictionary *commentDict in array) {
                SuperCommentModel *model = [[SuperCommentModel alloc] initWithDict:commentDict];
                [_leaveListArray addObject:model];
            }
            [self.tableView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

//留言
- (void)callLeavWordRequestWith:(NSString *)text {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"cid":self.cid,
                           @"description":text,
                           @"type":@"10"
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kSendComment];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            [self showTitle:responseObject[@"data"][@"message"]];
            NSDictionary *dataDict = responseObject[@"data"][@"comment"];
            _msgInputFeild.text = nil;
            SuperCommentModel *model = [[SuperCommentModel alloc] init];
            model.cid = dataDict[@"cid"];
            model.c_udid = dataDict[@"c_udid"];
            model.c_content = dataDict[@"c_content"];
            model.c_createtime = dataDict[@"c_createtime"];
            model.u_nickname = dataDict[@"u_nickname"];
            model.u_avatar = dataDict[@"u_avatar"];
            model.children = [NSMutableArray arrayWithCapacity:1];
            [_leaveListArray insertObject:model atIndex:0];
            NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            [indexPaths addObject: indexPath];
            [self.tableView beginUpdates];
            [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView endUpdates];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"留言列表";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [self setUpUI];
    [self leaveWordListRequest];
    // Do any additional setup after loading the view.
}
//监听键盘高度变化
-(void)keyboardFrameDidChange:(NSNotification*)notice
{
    NSDictionary * userInfo = notice.userInfo;
    NSValue * endFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endFrame = endFrameValue.CGRectValue;
    [UIView animateWithDuration:0.25 animations:^{
        _msgInputView.y = endFrame.origin.y - _msgInputView.height - kNAV_HEIGHT;
    }];
}
#pragma mark -- UI
- (void)setUpUI {
    _leaveListArray = [NSMutableArray arrayWithCapacity:1];
    [self creatTableView];
    [self.view addSubview:self.msgInputView];
    
}

- (void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT -kNAV_HEIGHT - 50)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
}

#pragma mark -- tableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _leaveListArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CallStarLeaveCell *cell = [CallStarLeaveCell loadNibCellWithTabelView:tableView];
    SuperCommentModel *model = _leaveListArray[indexPath.row];
    cell.commentModel = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}

#pragma mark -- 区头视图
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    SuperCommentModel *model = _leaveListArray[indexPath.row];
    CGSize maxSize = CGSizeMake(kSCREEN_WIDTH - 65, MAXFLOAT);
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14], NSForegroundColorAttributeName: [UIColor colorWithWhite:0.263 alpha:1.000]};
    CGSize textSize = [model.c_content boundingRectWithSize:maxSize
                                                         options:NSStringDrawingUsesLineFragmentOrigin
                                                      attributes:attributes
                                                         context:nil].size;
    CGSize richTextSize = CGSizeMake(textSize.width, textSize.height + 2);
    return richTextSize.height + 60;
}


#pragma mark -- 留言
- (void)clickSend:(UIButton *)sender {
    [_msgInputFeild resignFirstResponder];
    if (_msgInputFeild.text.length) {
        [self callLeavWordRequestWith:_msgInputFeild.text];
    }
}

#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_msgInputFeild resignFirstResponder];
    if (_msgInputFeild.text.length) {
        [self callLeavWordRequestWith:_msgInputFeild.text];
    } else {
        [self showTitle:@"请您输入留言内容"];
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
